//
//  AppDelegate.m
//  SleepingElf
//
//  Created by karong on 2023/6/7.
//

#import "AppDelegate.h"
#import "FirebaseCore.h"
#import "Firebase.h"
#import "BaseTabBarController.h"
#import "IQKeyboardManager.h"
#import "AppDelegateRequest.h"
#import "LoginController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFAudio/AVFAudio.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [FIRApp configure];
    [self initIQKeyboardManager];
    [self initMainPage];
    [self initRequest];
    
    return YES;
}

- (void)initIQKeyboardManager {
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    keyboardManager.shouldResignOnTouchOutside = YES;
    keyboardManager.enableAutoToolbar = NO;
    keyboardManager.keyboardDistanceFromTextField = 61 + 12;
    [keyboardManager registerTextFieldViewClass:[YYTextView class] didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
}

- (void)initMainPage {
    UIViewController *mainVC;
    if(appUserCenter.isLogin) {
        [appUserCenter getUserInfoRequest];
        BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
        nav.navigationBarHidden = YES;
        mainVC = nav;
    }
    else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
        LoginController *loginVC = [storyBoard instantiateInitialViewController];
        BaseNavigationController * loginNav = [[BaseNavigationController alloc]initWithRootViewController:loginVC];
        loginNav.navigationBarHidden = YES;
        mainVC = loginNav;
    }
    self.window.rootViewController = mainVC;
}

- (void)reloadMain {
    UIViewController * vc = self.window.rootViewController;
    if ([vc isKindOfClass:NSClassFromString(@"BaseNavigationController")]) {
        BaseNavigationController * nav = self.window.rootViewController;
        vc = nav.viewControllers.firstObject;
        UIViewController *mainVC;
        if ([vc isKindOfClass:NSClassFromString(@"BaseNavigationController")]) {
            BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseNavigationController new]];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        else {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
            LoginController *loginVC = [storyBoard instantiateInitialViewController];
            BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:loginVC];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        self.window.rootViewController = mainVC;
    }
    [self.window makeKeyAndVisible];
}

- (void)initRequest {
    [AppDelegateRequest updateServerTimeWithSuccess:^{
        NSLog(@"");
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        NSLog(@"");
    }];
}
#pragma mark - UISceneSession lifecycle
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    //    [[FBSDKApplicationDelegate sharedInstance]application:app openURL:url options:options];
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    //    [FBSDKAppEvents shared];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [self updateNowPlayingInfo];
}

- (void)updateNowPlayingInfo {
    MusicModel * music = [[PlayerManager shared]currentPlayingMusic];
    if (!music) {
        [self updateNowPlayingInfo:nil];
        return;
    }
    
    NSMutableDictionary *playInfo = [NSMutableDictionary new];
    NSDictionary *curDict = [[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo];
    if (curDict) {
        playInfo = [curDict mutableCopy];
    }
    NSString * songName = !SEIsNullOrEmpty(music.title)? music.title:WSLocalized(@"未知歌曲");
    NSString * singerName = [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"];
    [playInfo setObject:songName forKey:MPMediaItemPropertyTitle];      //歌曲
    [playInfo setObject:singerName forKey:MPMediaItemPropertyArtist];   //歌手
    
    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:music.cover] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image) {
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:image.size requestHandler:^UIImage * _Nonnull(CGSize size) {
                return image;
            }];
            if (artwork) {
                [playInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
            }
        }
    }];
    [self updateNowPlayingInfo:playInfo];
}

- (void)updateNowPlayingInfo:(NSDictionary *)playInfo{
    // 设置控制中心歌曲信息
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:playInfo];
    if (@available(iOS 13.0, *)) {
        if ([PlayerManager shared].isPlaying) {
            [MPNowPlayingInfoCenter defaultCenter].playbackState = MPNowPlayingPlaybackStatePlaying;
        }else {
            [MPNowPlayingInfoCenter defaultCenter].playbackState = MPNowPlayingPlaybackStatePaused;
        }
    }
}

@end
